package com.meizu.control;

import com.alibaba.fastjson.JSONObject;
import com.meizu.dao.CartDao;
import com.meizu.dao.DetailDao;
import com.meizu.entity.Address;
import com.meizu.entity.Cart;
import com.meizu.entity.Detail;
import com.meizu.entity.User;
import com.meizu.service.AddressService;
import com.meizu.service.DetailService;
import com.meizu.utils.BaseServlet;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * 订单确认 的控制层操作类
 * @date 2023/4/18
 **/
@WebServlet("/orderSureServlet")
@MultipartConfig
public class OrderSureServlet extends BaseServlet {
    AddressService as=new AddressService();
    DetailDao dd=new DetailDao();
    DetailService ds=new DetailService();
    CartDao cd=new CartDao();
    @Override
    public String excute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return "f:admin/error";
    }
    public String excutrr(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Object use=session.getAttribute("user");
        session.removeAttribute("hj");
        if (use instanceof User){
            User user=(User)use;
            String count = request.getParameter("count");//获取数量（详情页传递）
            Integer did = (Integer) session.getAttribute("did");//获取商品详情ID（详情页传递）
            String[] cids = request.getParameterValues("cid");//获取购物车ID数组（购物车页面传递）
            List<Detail> list = new ArrayList<>();
            Integer heji = 0;
            if (cids != null) {//购物车ID数组不为空，则进行转化并存入session，传给OrderServlet的create方法
                int[] cid1 = Arrays.stream(cids).mapToInt(Integer::parseInt).toArray();
                for (int i : cid1) {
                    Cart cart = cd.selectByCid(i);
                    if (cart == null) {
                        return "f:admin/error";
                    }
                }
                Integer[] cid = Arrays.stream(cid1).boxed().toArray(Integer[]::new);
                session.setAttribute("cid", cid);
            }
            if (count != null && !"".equals(count)) {//如果存在数量，则是从详情页进入
                Integer c = Integer.parseInt(count);
                Detail s = ds.selectXQ1(did, c);//通过did和count查询并组装一个detail对象
                if (s.getDprice()==null){
                    return "f:admin/error";
                }
                list.add(s);
                heji = s.getDprice() * c;
                session.setAttribute("count", c);
                session.setAttribute("did", did);
            } else {
                for (String a : cids) {
                    Integer c = Integer.valueOf(a);
                    Detail s = ds.selectXQ(c);//通过购物车ID查询组装成一个detail对象
                    list.add(s);
                    heji += s.getDprice() * s.getCount();
                }
            }
            request.setAttribute("cid", list);
            session.setAttribute("hj", heji);
            session.setAttribute("len", list.size());
            List<Address> address = as.selectAll(user.getUid());
            request.setAttribute("address", address);
            Address adres = as.selectMrzYi(user.getUid());
            if (adres != null) {
                session.setAttribute("addressNum", adres.getAid());
            } else {
                List<Address> aadd = as.selectAll(user.getUid());
                if (aadd.size() != 0) {
                    session.setAttribute("addressNum", aadd.get(0).getAid());
                } else {
                    request.setAttribute("aa", aadd);
                    request.setAttribute("error", "您没有地址，请添加地址！！");
                }
            }
            return "f:ordersure";
        }else {
            return "f:admin/error";
        }
    }

    //删除地址
    public JSONObject deleteOrderSure(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String Id=req.getParameter("id");
        Integer ID=Integer.parseInt(Id);
        Integer del=as.deleteByaid(ID);
        JSONObject json=new JSONObject();
        json.put("del",del);
        User user=(User)session.getAttribute("user");
        List<Address> u=as.selectAll(user.getUid());
        if (u.size()!=0){
            session.setAttribute("addressNum",u.get(0).getAid());
        }
        return json;
    }
    //新增地址
    public JSONObject insertOrderSure(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        resp.setContentType("application/json;charset=utf-8");
        User user=(User)session.getAttribute("user");
        String mz=req.getParameter("name");
        String dh=req.getParameter("phone");
        String shen=req.getParameter("shen");
        String si=req.getParameter("shi");
        String qv=req.getParameter("qu");
        String jd=req.getParameter("jie");
        String dz=req.getParameter("dizi");
        String mr=req.getParameter("set_default");
        //新增将其他的默认值为1的改为0;
            Address ad=as.selectMrzYi(user.getUid());
            if(ad!=null){
                as.udateMoren(user.getUid());
            }
        JSONObject json=new JSONObject();
        Address address=new Address(null,user.getUid(),mz,shen,si,qv,jd,dz,dh,Integer.parseInt(mr));

        as.insertAll(address);
        List<Address> u=as.selectAll(user.getUid());
        session.setAttribute("addressNum",u.get(0).getAid());
        req.setAttribute("aa",u);
        req.setAttribute("error","");
        String user1=JSONObject.toJSONString(u);
        json.put("add",user1);
        return json;
    }
    //回显地址
    public String hiuxianDZ(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("application/json;charset=utf-8");
        String id=request.getParameter("id");
        session.setAttribute("ID",id);
        Address address=as.selectOne(Integer.parseInt(id));
        String json=JSONObject.toJSONString(address);
        return json;
    }
    //修改地址
    public String updateDZ(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.setContentType("application/json;charset=utf-8");
        User user=(User)session.getAttribute("user");
        Object obj=session.getAttribute("ID");
        Integer id=Integer.parseInt(obj.toString());
        String name=request.getParameter("mz");
        String phone=request.getParameter("dh");
        String sheng=request.getParameter("shen");
        String shi=request.getParameter("shi");
        String qu=request.getParameter("qu");
        String jie=request.getParameter("jd");
        String dzxq=request.getParameter("dz");
        //将其他默认值为1的修改为0;
        as.udateMoren(user.getUid());
        Address address=new Address(id,user.getUid(),name,sheng,shi,qu,jie,dzxq,phone,1);
        Integer r=as.updateByaid(address);
        if (r>0){
            System.out.println("修改成功！！");
        }
        List<Address> addressList=as.selectAll(user.getUid());
        session.setAttribute("addressNum",addressList.get(0).getAid());
        String json=JSONObject.toJSONString(addressList);
        return json;
    }
    //修改地址默认值
    public String reviseMR(HttpServletRequest request,HttpServletResponse response) throws  Exception{
        String Id=request.getParameter("id");
        Integer id=Integer.parseInt(Id);
        User user=(User)session.getAttribute("user");
        //将其他默认值为1的修改为0;
        Address ad=as.selectMrzYi(user.getUid());
        if(ad!=null){
            as.udateMoren(user.getUid());
        }
        as.updateDefault(1,id);
        List<Address> addresses=as.selectAll(user.getUid());
        session.setAttribute("addressNum",addresses.get(0).getAid());
        return JSONObject.toJSONString(addresses);
    }
}
